<template>
  <section>
    <el-row>
      <el-card>
        <el-col :span="24">
          <div>
            <el-row :gutter="4">
              <el-form :inline="true" label-width="60px">
                <el-form-item label="标题:">
                  <el-input
                    placeholder="请输入标题"
                    v-model="searchDto.title"
                  ></el-input>
                </el-form-item>
                <el-form-item v-if="activeName !== 'my'" label="发送人:">
                  <el-input
                    placeholder="请输入发送人"
                    v-model="searchDto.sender"
                  ></el-input>
                </el-form-item>
                <el-form-item label="时间:">
                  <el-date-picker
                    v-model="value4"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                  ></el-date-picker>
                </el-form-item>
                <el-form-item class="clear_item-margin-bottom">
                  <el-button
                    type="primary"
                    icon="el-icon-search"
                    @click="search()"
                    >查询
                  </el-button>
                  <el-button
                    type="primary"
                    icon="el-icon-s-open"
                    @click="clear()"
                    >重置
                  </el-button>

                </el-form-item>
              </el-form>
            </el-row>
          </div>
          <div class="table_content">
            <el-tabs v-model="activeName" @tab-click="handleClick1">
              <el-tab-pane
                v-for="(item, index) in activeNameList"
                :key="index"
                :label="item.label + '(' + findNum(item.name) + ')'"
                :name="item.name"
              ></el-tab-pane>
              <el-tab-pane
                v-if="currentTokenUser && showAll()"
                :label="'全部' + '(' + findNum('all') + ')'"
                name="all"
              ></el-tab-pane>
            </el-tabs>
            <page-table
              ref="multipleSelection"
              :page-data="pageData"
              :loading="loading"
              :do-get-page-data="getPageData"
              :select-change="handleSelectionChange"
            >
              <el-table-column
                :selectable="selectable"
                align="center"
                key="selection"
                type="selection"
                width="55"
              ></el-table-column>
              <el-table-column
                width="220"
                prop="title"
                show-overflow-tooltip
                key="title"
                label="标题"
                align="left"
              >
                <template slot-scope="scope">
                  <span @click="taskEdit(scope.row)" style="cursor: pointer">
                    <span v-if="scope.row.type === 'BACK'" style="color: red;"
                      >【退回】</span
                    >
                    <span
                      v-if="scope.row.priority === 'SPECIAL_URGENT'"
                      style="color: red;"
                      >【特急】</span
                    >
                    <a class="task_title_a">{{ scope.row.title }}</a>
                  </span>
                </template>
              </el-table-column>
              <el-table-column
                show-overflow-tooltip
                prop="flowName"
                label="流程"
                key="flowName"
                align="center"
              >
              </el-table-column>
              <el-table-column
                prop="stepName"
                label="步骤"
                align="center"
                key="stepName"
                show-overflow-tooltip
              >
              </el-table-column>
              <el-table-column
                v-if="activeName !== 'my'"
                prop="senderName"
                label="发送人"
                key="senderName"
                show-overflow-tooltip
                align="center"
              >
              </el-table-column>
              <el-table-column
                show-overflow-tooltip
                prop="receiveTime"
                label="接收日期"
                key="receiveTime1"
                align="center"
              >
              </el-table-column>
              <el-table-column
                label="停留时间"
                prop="receiveTime"
                key="waitTime1"
                align="center"
                v-if="activeName !== 'all'"
                show-overflow-tooltip
              >
                <template slot-scope="scope">
                  <span>{{
                    getWaitDays(scope.row.receiveTime, scope.row.completedTime)
                  }}</span>
                </template>
              </el-table-column>
              <el-table-column
                prop="instanceStatus"
                label="流程状态"
                key="instanceStatus"
                show-overflow-tooltip
                align="center"
              >
                <template slot-scope="scope">
                  <sz-badge
                    :value="
                      !scope.row.archiveStatus
                        ? scope.row.instanceRunStatus &&
                          scope.row.instanceRunStatus == 'END'
                          ? '已终止'
                          : scope.row.instanceStatus
                          ? '已完结'
                          : '未完结'
                        : '已归档'
                    "
                    :type="statusStyle(scope.row)"
                  ></sz-badge>
                </template>
              </el-table-column>
              <el-table-column
                label="管理"
                width="150"
                key="manage"
                align="center"
                fixed="right"
              >
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    size="mini"
                    @click="showFlowNode(scope.row)"
                  >
                    流程轨迹
                  </el-button>
                  <!-- 我的申请添加删除 -->
                  <template v-if="activeName == 'my'">
                    <el-button
                      v-if="!scope.row.instanceStatus"
                      type="text"
                      size="mini"
                      @click="endFlowNode(scope.row)"
                    >
                      终止
                    </el-button>
                  </template>
                  <!-- 终止后可删除 -->
                  <template v-if="activeName == 'end'">
                    <el-button
                      type="text"
                      size="mini"
                      @click="delFlowNode(scope.row)"
                    >
                      删除
                    </el-button>
                  </template>
                </template>
              </el-table-column>
            </page-table>
          </div>
        </el-col>
      </el-card>
    </el-row>
    <el-dialog
      :close-on-click-modal="false"
      :visible.sync="showFlowNodeHistory"
      v-if="showFlowNodeHistory"
      title="流程轨迹:"
      width="40%"
      destroy-on-close
    >
      <el-row>
        <el-col>
          <flow-node-history :task-id="curTaskId"></flow-node-history>
        </el-col>
        <el-col :span="24" class="mt20" slot="footer">
          <span>
            <el-button size="small" @click="showFlowNodeHistory = false"
              >取消</el-button
            ></span
          >
        </el-col>
      </el-row>
    </el-dialog>
  </section>
</template>
<script>
import Moment from "moment";
import flowNodeHistory from "./flowNodeHistory";
import baseDingAuth from "@/libs/BaseAuth";
import { formatTime } from "../../../filters";
import _ from "lodash";

export default {
  extends: baseDingAuth,
  created() {},
  data() {
    return {
      summaryListNum: [],
      multipleSelection: [],
      curTaskId: "",
      showFlowNodeHistory: false,
      loading: false,
      pageData: {},
      value4: [],
      searchDto: {
        categoryId: "",
        pageSize: 10,
        pageIndex: "",
        title: "",
        sender: "",
        flowId: this.$route.query.flowId,
        startTime: "",
        endTime: "",
        status: "",
        copy: "",
        type: ""
      },
      currentTokenUser: JSON.parse(window.sessionStorage.getItem("userInfo")),
      activeName: "wait"
    };
  },
  computed: {
    activeNameList() {
      let list = [
        { label: "待办", name: "wait" },
        { label: "已办", name: "completed" }
      ];
      if (this.$route.query.hideTab !== "true") {
        list = [
          { label: "待办", name: "wait" },
          { label: "已办", name: "completed" },
          { label: "待阅", name: "waitRead" },
          { label: "已阅", name: "read" },
          { label: "我申请的", name: "my" },
          { label: "终止", name: "end" }
        ];
      }
      return list;
    }
  },
  watch: {
    $route(to, from) {
      this.searchDto.flowId = this.$route.query.flowId;
      this.activeName = "wait";
      this.getPageData();
      this.getPageData1();
    }
  },
  methods: {
    delFlowNode({ id }) {
      this.$confirm("确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.API.deleteEndWorkflowTaskById({ id }).then(ret => {
          this.$message({
            type: "success",
            message: "删除成功!"
          });
          this.getPageData();
          this.getPageData1();
        });
      });
    },
    endFlowNode(row) {
      this.$confirm("确认终止?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.API.endFlowByInstanceId({ id: row.instanceId }).then(res => {
          this.$message({
            message: "终止成功",
            type: "success"
          });
          this.getPageData();
          this.getPageData1();
        });
      });
    },
    showAll() {
      let tem = false;
      if (this.$route.query.userIds) {
        let userIdArr = this.$route.query.userIds.split(",");
        userIdArr.some(item => {
          item == this.currentTokenUser.user.userId && (tem = true);
        });
      }
      return tem;
    },
    //禁用多选框
    selectable(row, index) {
      return !(row.instanceStatus == true || row.instanceRunStatus);
    },
    // 状态颜色设置
    statusStyle(row) {
      let cls = "";
      switch (row.instanceStatus) {
        case true:
          cls = "success";
          break;
        default:
          cls = "warning";
          break;
      }
      switch (row.instanceRunStatus) {
        case "END":
          cls = "danger";
          break;
      }
      return cls;
    },
    getWaitDays(value, completedTime) {
      if (value !== "" && value !== undefined && value !== null) {
        let date = new Date(formatTime(new Date(value), "yyyy-MM-dd 00:00:00"));
        let nowData = completedTime
          ? new Date(formatTime(new Date(completedTime), "yyyy-MM-dd 00:00:00"))
          : new Date(formatTime(new Date(), "yyyy-MM-dd 00:00:00"));
        let dateSpan = nowData - date;
        console.log(dateSpan);
        dateSpan = Math.abs(dateSpan);
        let iDays = Math.floor(dateSpan / (24 * 3600 * 1000));
        return iDays + "天";
      }
    },
    //批量催办
    batchUrging() {
      if (this.multipleSelection && this.multipleSelection.length == 0) {
        this.$message({
          message: "请至少勾选一条数据",
          type: "warning"
        });
      } else {
        let arr = [];
        this.multipleSelection.map(item => {
          arr.push(item.instanceId);
        });
        this.API.remindByInstanceList({ body: arr }).then(ret => {
          this.success(ret.data.value);
          this.$refs.multipleSelection.clearOption();
          this.getPageData(1);
          this.getPageData1();
        });
      }
    },
    //多选
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    async loadData() {
      this.currentTokenUser = await JSON.parse(
        window.sessionStorage.getItem("userInfo")
      );
      this.getPageData();
      this.getPageData1();
    },
    /**
     * 描述：创建新流程
     * 时间： 2020/12/12
     */
    applyWorkflow() {
      if (this.$route.fullPath.indexOf("other") !== -1) {
        this.$router.push({
          path: "/workflow/apply",
          query: { flowId: this.$route.query.flowId, back: true }
        });
      } else {
        let routeData = this.$router.resolve({
          path: "/workflow/apply",
          query: { flowId: this.$route.query.flowId }
        });
        this.openTabPage(routeData.href);
      }
    },
    // 显示流程轨迹面板
    showFlowNode(row) {
      this.curTaskId = row.id;
      this.showFlowNodeHistory = true;
    },
    // 获取待办，已办任务列表
    getWaitTaskData(val) {
      let tem = Object.assign(this.searchDto, val);
      this.API.getWorkflowTaskPageList(tem)
        .then(res => {
          this.pageData = res.data;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    //查询所有
    getInstance(val) {
      let tem = Object.assign(this.searchDto, val);
      this.API.getWorkflowTaskInstancePageList(tem)
        .then(ret => {
          this.pageData = ret.data;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 获取我发起的
    getMySendData(val) {
      let tem = Object.assign(this.searchDto, val);
      this.API.getWorkflowTaskInstanceLaunchPageList(tem)
        .then(res => {
          this.pageData = res.data;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // // 获取我经办的
    // getMyHandleData(val) {
    //   let tem = Object.assign(this.searchDto, val);
    //   this.API.getWorkflowTaskInstanceHandlePageList(tem)
    //     .then(res => {
    //       this.pageData = res.data;
    //     })
    //     .finally(() => {
    //       this.loading = false;
    //     });
    // },
    handleClick1() {
      this.searchDto.pageIndex = 1;
      this.handleClick();
    },
    handleClick(val) {
      this.loading = true;
      switch (this.activeName) {
        case "wait":
          this.searchDto.status = "0";
          this.searchDto.copy = false;
          this.searchDto.type = "";
          this.getWaitTaskData(val);
          break;
        case "completed":
          this.searchDto.status = "1";
          this.searchDto.copy = false;
          this.searchDto.type = "";
          this.getWaitTaskData(val);
          break;
        case "waitRead":
          this.searchDto.status = "0";
          this.searchDto.copy = true;
          this.searchDto.type = "COPY_FOR";
          this.getWaitTaskData(val);
          break;
        case "read":
          this.searchDto.status = "1";
          this.searchDto.copy = true;
          this.searchDto.type = "COPY_FOR";
          this.getWaitTaskData(val);
          break;
        case "end":
          // ! 实例终止tag
          this.searchDto.status = 2;
          this.searchDto.copy = "";
          this.searchDto.type = "";
          this.getMySendData(val);
          break;
        case "my":
          this.searchDto.status = "";
          this.searchDto.type = "";
          this.searchDto.copy = "";
          this.getMySendData(val);
          break;
        case "all":
          this.searchDto.status = "";
          this.searchDto.type = "";
          this.searchDto.copy = "";
          this.getInstance(val);
          break;
      }
    },
    // 跳转任务处理
    taskEdit(row) {
      if (this.$route.fullPath.indexOf("other") !== -1) {
        this.$router.push({
          path: "/workflow/apply",
          query: { flowId: row.flowId, taskId: row.id, back: true }
        });
      } else {
        let routeData = this.$router.resolve({
          path: "/workflow/apply",
          query: { flowId: row.flowId, taskId: row.id }
        });
        this.openTabPage(routeData.href);
      }
    },
    getPageData(val) {
      this.searchDto.startTime = "";
      this.searchDto.endTime = "";
      if (this.value4 && this.value4.length > 0) {
        this.searchDto.startTime = Moment(this.value4[0]).format("YYYY-MM-DD");
        this.searchDto.endTime = Moment(this.value4[1]).format("YYYY-MM-DD");
      }
      this.handleClick(val);
    },
    findNum(val) {
      let num = 0;
      if (this.summaryListNum && this.summaryListNum.length === 7) {
        let obj = this.summaryListNum.find(item => item.name == val);
        num = obj.num1;
      }
      return num;
    },
    getPageData1(val) {
      this.summaryListNum = [];
      let arr = [
        { key: "wait", status: "0", copy: false, type: "" },
        {
          key: "completed",
          status: "1",
          copy: false,
          type: ""
        },
        { key: "waitRead", status: "0", copy: true, type: "COPY_FOR" },
        { key: "read", status: "1", copy: true, type: "COPY_FOR" },
        { key: "my", status: "", copy: "", type: "" },
        { key: "end", status: 2, copy: "", type: "" },
        {
          key: "all",
          status: "",
          copy: "",
          type: "",
          userIds: this.$route.query.userIds
        }
      ];
      let searchDto1 = _.clone(this.searchDto);
      arr.map(item => {
        searchDto1.status = item.status;
        searchDto1.copy = item.copy;
        searchDto1.type = item.type;
        // item.key == "all" &&
        //   this.showAll() &&
        //   (searchDto1.userIds = item.userIds);
        let tem = Object.assign(searchDto1, val);
        if (item.key == "my" || item.key == "end") {
          this.API.getWorkflowTaskInstanceLaunchPageList(tem).then(res => {
            console.log(res.data);
            this.summaryListNum.push({
              name: item.key,
              num1: res.data.total
            });
          });
        } else if (item.key == "all" && this.showAll()) {
          this.API.getWorkflowTaskInstancePageList(tem).then(res => {
            this.summaryListNum.push({
              name: item.key,
              num1: res.data.total
            });
          });
        } else {
          this.API.getWorkflowTaskPageList(tem).then(res => {
            console.log(res.data);
            this.summaryListNum.push({
              name: item.key,
              num1: res.data.total
            });
          });
        }
      });
      console.log(this.summaryListNum, "num");
    },
    search() {
      this.getPageData(1);
      this.getPageData1();
    },
    clear() {
      this.searchDto = {
        categoryId: "",
        pageSize: 10,
        title: "",
        sender: "",
        flowId: this.$route.query.flowId,
        startTime: "",
        endTime: "",
        status: "",
        copy: "",
        type: ""
      };
      this.value4 = [];
      this.getPageData(1);
      this.getPageData1();
    }
  },
  components: {
    flowNodeHistory
  }
};
</script>
<style scoped></style>
